#!/usr/bin/env python

import sys
import json
from time import strptime

def mapper():
    DEBUG=0
    framewidth=2
    bucket=[]
    term=''
    li=section_head=0
    ctime=e_time=s_time=0
    mtag={}
    ctag=0
    stag=0
    for line in sys.stdin:
        line = line.decode('gbk','ignore').strip().encode('utf-8')
        li+=1
        if len(line)>2:
            if len(line.split('\t'))!=7:
                continue
            (session_id,date_time,modif_tag,query_term,url,satif_tag,act_type) = line.split('\t')
            date_time=strptime(date_time, '%d/%b/%Y:%H:%M:%S')
            date=str(date_time.tm_year)+'/'+str(date_time.tm_mon)+'/'+str(date_time.tm_mday)
            ctime=date_time.tm_hour*60*60+date_time.tm_min*60+date_time.tm_sec
            if query_term==term:
                if len(url)>1:
                    ctag|=1
                stag|=int(satif_tag)
                e_time=ctime
            
            else:
                if term!='':
                    distance=li-position-section_head
                    if DEBUG:
                        print ctime, s_time, e_time, 'a'
                    bucket.append((term,s_time,e_time,mtag,ctag,stag,position,distance))
                position=li-section_head
                term=query_term
                if DEBUG:
                    print ctime, s_time, e_time
                s_time=ctime
                mtag=modif_tag
                ctag=0
                if len(url)>1:
                    ctag=1
                stag=int(satif_tag)
                     
        else:
            if len(bucket)<1:
                section_head=li
                bucket=[]
                continue
            
            if DEBUG:
                print ctime, s_time, e_time, 'b'
            bucket.append((term,s_time,e_time,mtag,ctag,stag,position,distance))
            term=''

            for i in range(len(bucket)-1):
                ceil=i+framewidth+1
                if ceil > len(bucket):
                    ceil=len(bucket)
                for j in range(i+1,ceil):
                    btime=bucket[j][1]-bucket[i][2]
                    bm_tag=[{str(bucket[i][3]):1},{str(bucket[j][3]):1}]
                    bc_tag=[bucket[i][4],bucket[j][4]]
                    bs_tag=[bucket[i][5],bucket[j][5]]
                    ts_tag=(not bucket[i][5])&bucket[j][5]
                    poq=bucket[i][6] #position of oquery
                    loq=bucket[i][7] #length of lines of oquery
                    pq=bucket[j][6] #position of query
                    lq=bucket[j][7] #length of lines of query
                    step={str(j-i):1}
                    pvalue={'':((session_id,date,poq,loq,pq,lq),btime,step,bm_tag,bc_tag,bs_tag,ts_tag)}
                    pvalue=json.dumps(pvalue)
                    print '%s||| %s\t1\t%s' % (bucket[i][0],bucket[j][0],pvalue)
            section_head=li
            bucket=[] 

if __name__ == '__main__':
    mapper()
